#include "TwPick.h"
#include "../TwEngineDx.h"

bool TwPick::IsIntersect(const TwRect3d& twRec3d)
{
	 
	
	g_Render->GetDevice()->GetTransform(D3DTS_PROJECTION, &m_matProjection);
	g_Render->GetDevice()->GetTransform(D3DTS_VIEW, &m_matView);
	g_Render->GetDevice()->GetTransform(D3DTS_WORLD, &m_matWorld);

	// use the mouse coordinates to get the mouse angle
	GetCursorPos(&m_MousePos);

	
	float xAngle = (((2.0f * m_MousePos.x) / SCREEN_WIDTH) - 1.0f) /m_matProjection(0, 0);
	float yAngle = (((-2.0f * m_MousePos.y) / SCREEN_HEIGHT) + 1.0f) / m_matProjection(2, 2);

	
	m_origin = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
	m_direction = D3DXVECTOR3(xAngle, yAngle,1.0f);

	// find the inverse matrix
	D3DXMatrixInverse(&m_matInverse, NULL, &(m_matWorld * m_matView));

	// convert origin and direction into model space
	D3DXVec3TransformCoord(&m_origin, &m_origin, &m_matInverse);
	D3DXVec3TransformNormal(&m_direction, &m_direction, &m_matInverse);
	D3DXVec3Normalize(&m_direction, &m_direction);
	

	D3DXVECTOR3 min3(twRec3d.x0,twRec3d.y0,twRec3d.z0),max3(twRec3d.x1,twRec3d.y1,twRec3d.z1);

	return D3DXBoxBoundProbe(&min3,&max3,&m_origin,&m_direction);

}